import express from 'express';
// import type {Request} from "express"
import logger from "morgan"
import path from "path";
import cookieParser from "cookie-parser";
import { jwtCheck } from "../utils/jwt"
import user from "./routes/user";
import test from "./routes/test";
import aiImg from "./routes/aiImg"
import xcx from "./routes/xcx"
import s from "./routes/stzb"

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html')
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());


//使用跨域中间件
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', "*"); // 如果携带凭证，则不能使用 *  
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization,token'); // 添加了 token  
    if (req.method === 'OPTIONS') {
        res.sendStatus(200); // 对于OPTIONS请求，直接返回200状态码  
    } else {
        res.header('Access-Control-Allow-Credentials', "true"); // 如果需要携带凭证  
        next();
    }
});

app.use("/api", [s])


app.use((req, res, next) => {
    if (req.url.startsWith("/api/user") || req.url.startsWith("/public") || req.url.startsWith("/api/xcx/login")) {
        next();
    } else {
        if (jwtCheck(req)) {
            next();
        } else {
            return res.send({
                code: 403,
                msg: "登录过期，请重新登录"
            })
        }
    }
})

app.use('/public', (req, res) => {
    if (jwtCheck(req)) {
        const url = req.url.split('?')[0]
        return res.sendFile(path.resolve(__dirname,"../public/"+url));
    } else {
        return res.send({
            code: 403,
            msg: "登录过期，请重新登录"
        })
    }
});


app.use("/api", [xcx])
app.use("/api", [user, aiImg]);

export default { app, port: 3000 };
